import axios, {AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig} from 'axios'

const service: AxiosInstance = axios.create({
    timeout: 30000
})

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config
    },
    (error: AxiosError) => {
        console.log(error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            const data = response.data;
            if (data.code === 500) {
                alert(data.msg)//提示错误信息
            }
            return response
        } else {
            return Promise.reject(new Error(`Unexpected response status: ${response.status}`))
        }
    },
    (error: AxiosError) => {
        if (error.response && error.response.status === 500) {
            window.alert('服务器错误，请稍后再试。')
        } else if (error.response && error.response.status === 404) {
            window.alert('请求过于频繁，请稍后再试！')
        } else {
            console.log(error)
        }
        return Promise.reject(error)
    }
)

export default service
